/**
	Copyright (c) 2010 ATTi 
	All rights reserved.
	Author: Michael Shu
	Date: 11/8/2010
*/


global class AASUserBatchUpdateDaily implements Schedulable, Database.Batchable<sObject>, Database.Stateful{
	/* To schedule it at 2:00am every day , in Anonymous Blocks and execute below commands
	   AASUserBatchUpdateDaily a0 = new AASUserBatchUpdateDaily();
	   String sch0 = AASUserBatchUpdateDaily.CRON_EXP_AAS;
	   System.schedule('Schedule Batch update AAS at 2:00am daily', sch0, a0);	
	*/
	public static String CRON_EXP_AAS  = '0 00 2 * * ?'; 
	public static String AAS_Profile1 = '%Advanced Ad Solutions%';
	public static String AAS_Profile2 = '%AAS%';
	public static String AccountObj = 'Account';
	public static String OpportunityObj = 'Opportunity';
	public static String LeadObj = 'Lead';
	private String objName, fields, recordTypeIdStr, ownerIdStr, condition;
	private Map<ID, User> AASUsers;

	global AASUserBatchUpdateDaily(){
	}
	
	global AASUserBatchUpdateDaily(String obj, Map<ID, User> usrs){
		this.objName = obj;
		this.AASUsers = usrs;
		if(this.objName == LeadObj){
			this.fields = 'Id, OwnerId, Office__c, Office_To_Opp__c, Sales_Region__c, Sales_Region_To_Opp__c, Pre_Sale_Manager_To_Acc__c, Post_Sale_Manager_To_Acc__c ';
			this.condition = ' and IsConverted = false ';
		}else if(this.objName == OpportunityObj){
			this.fields = 'Id, OwnerId, Office__c, Sales_Region__c , Pre_Sale_Manager__c, Post_Sale_Manager__c ';
			this.condition = ' and Probability < 90.0';			
		}else{
			this.fields = 'Id, OwnerId, Office__c, Sales_Region__c , Pre_Sale_Manager__c, Post_Sale_Manager__c ';
			this.condition = '';
		}
		ownerIdStr = setToString(usrs.keySet());
		if(this.objName == AccountObj){
			Set<ID> aasAccRecordTyeId = AASFieldUpdateHelperClass.getAccountAASRecordTypeID();
			recordTypeIdStr = setToString(aasAccRecordTyeId);
		}else if(this.objName == OpportunityObj){
			Set<ID> oppAASRecordTypeID = AASFieldUpdateHelperClass.getOpportunityAASRecordTypeID();
			recordTypeIdStr = setToString(oppAASRecordTypeID);
		}else if(this.objName == LeadObj){
			Set<ID> leadAASRecordTypeID = AASFieldUpdateHelperClass.getLeadAASRecordTypeID(); 
			recordTypeIdStr = setToString(leadAASRecordTypeID);
		}
		
	}
	
	private String setToString(Set<ID> ids){
		String str = '';
		for(ID id : ids){
			if(id != null){
				str += '\'' + id + '\'' + ',';
			}
		}
		if(str.endsWith(',')){
		    str = str.substring(0, str.lastIndexOf(',')); //trim last comma;
		}
		str = ' ( ' + str + ' ) ';
		return str;
	}
		
	global void execute (SchedulableContext SC){
		//Datetime oneDaysAgo = Datetime.now().addDays(-1);
		Map<ID, User> users = new Map<ID, User>([ select ID, Pre_Sale_Manager__c, Post_Sale_Manager__c, Office__c, Sales_Region__c from User 		                                             
		                                          where isActive = true and (Profile.Name like: AAS_Profile1 or Profile.Name like: AAS_Profile2)]);
		if(!users.isEmpty()){
			AASUserBatchUpdateDaily accBatch = new AASUserBatchUpdateDaily(AccountObj, users);
			Id accBatch_id = database.executebatch(accBatch);
			
			AASUserBatchUpdateDaily leadBatch = new AASUserBatchUpdateDaily(LeadObj, users);
			Id leadBatch_id = database.executebatch(leadBatch);

			AASUserBatchUpdateDaily oppBatch = new AASUserBatchUpdateDaily(OpportunityObj, users);
			Id oppBatch_id = database.executebatch(oppBatch);
		}
	}	
	
	global Database.QueryLocator start(Database.BatchableContext BC){	
		String query = 	' select ' + this.fields +  ' from ' + this.objName + ' where RecordTypeId IN ' + recordTypeIdStr + ' and OwnerId IN ' + ownerIdStr + ' ' + condition;
		System.debug(' query = ' + query); 
		return Database.getQueryLocator(query);
	}

	global void execute(Database.BatchableContext BC, List<Sobject> scope){
		System.debug(' this.objName = ' + this.objName);
		if(this.objName == AccountObj){
			AASFieldUpdateHelperClass.updateAccts(scope, this.AASUsers, AASFieldUpdateHelperClass.isUserUpdate);
		}else if(this.objName == OpportunityObj){
			AASFieldUpdateHelperClass.updateOpps(scope, this.AASUsers, AASFieldUpdateHelperClass.isUserUpdate);
		}else if(this.objName == LeadObj){
			AASFieldUpdateHelperClass.updateLeads(scope, this.AASUsers, AASFieldUpdateHelperClass.isUserUpdate);
		}
	}
	
	global void finish(Database.BatchableContext BC){
	}		
}